<!--添加与编辑专栏组件-->
<template>
  <div class="app-container">
    <el-form :model="postForm" ref="postForm" label-width="180px" label-position="right">
      <!-- 基础设置 -->
      <div class="font-family-h font-bold margin-t50 margin-b40">
        <i class="square"></i>基本信息
      </div>
      <el-form-item label="专栏名称：" prop="name">
        <el-input
          :maxlength="80"
          style="width:420px;"
          v-model="postForm.name"
          placeholder="请输入名称，建议15个汉字以内，最多支持40个汉字"
        ></el-input>
      </el-form-item>
      <el-form-item label="专栏简介：" prop="intro">
        <el-input style="width:420px;" v-model="postForm.intro" placeholder="请输入简介"></el-input>
      </el-form-item>
      <el-form-item label="所属分类：" prop="intro">
        <el-select v-model="postForm.classId" placeholder="请选择">
          <el-option
            v-for="item in classList"
            :key="item.classname"
            :label="item.classname"
            :value="item.classId"
          ></el-option>
        </el-select>
        <el-button type="primary" @click="$router.push({path:'/knowledge/createSort'})">新建分类</el-button>
      </el-form-item>
      <el-form-item label="专栏价格：" prop="price">
        <el-input
          type="number"
          min="0"
          v-model="postForm.price"
          placeholder="请输入内容"
          class="width110"
        ></el-input>元
      </el-form-item>
      <el-form-item label="虚拟起售数：" prop="initSales">
        <el-input
          type="number"
          min="0"
          v-model="postForm.initSales"
          placeholder="请输入内容"
          class="width110"
        ></el-input>
        <span class="el-form-tip">前端订阅量=虚拟起售数+实际订阅量</span>
      </el-form-item>
      <el-form-item label="专栏课程：">
        <el-button @click="showCourse = true,selectCourse()">选择课程</el-button>
        <ul>
          <li v-for="(item,index) in courseArray" :key="index">{{index+1}}:{{item.name}}</li>
        </ul>
      </el-form-item>
      <el-form-item label="是否上架:" prop="status">
        <el-radio-group v-model="postForm.status">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否更新:" prop="isUpdating">
        <el-radio-group v-model="postForm.isUpdating">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="排序：" prop="sort">
        <el-input type="number" v-model="postForm.sort" placeholder="请输入排序" class="width110"></el-input>
        <span class="el-form-tip">（数值越大排序越前）</span>
      </el-form-item>

      <el-form-item label="专栏封面(宽180*高120)：" prop="cover">
        <div class="clearfix">
          <img
            class="fl margin-r"
            :src="postForm.cover"
            @error="setDefultImg"
            width="180"
            height="120"
            alt
          />
          <el-upload
            class="fl"
            ref="avatarUpload"
            name="avatar"
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            :auto-upload="true"
            style="width: 420px"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3m</div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="专栏详情：" prop="columnDetail">
        <tinymce :height="350" v-model="postForm.description" style="width: 600px;float: left;"></tinymce>
      </el-form-item>
    </el-form>
    <el-button type="primary" icon="el-icon-check" @click="submitForm">保存</el-button>

    <el-dialog title="选择课程" :visible.sync="showCourse" width="40%">
      <el-input placeholder="请输入课程名或讲师姓名进行搜索" v-model="courseName" style="width:70%"></el-input>
      <el-button type="primary" icon="el-icon-search" size="small" @click="searchCourse()">搜索</el-button>
      <el-table
        ref="multipleTable"
        :data="courseList"
        tooltip-effect="dark"
        height="300"
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="price" label="价格"></el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showCourse = false">取 消</el-button>
        <el-button type="primary" @click="confirmCourse()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import "vue-multiselect/dist/vue-multiselect.min.css";
import { getCourseList } from "@/api/course";
import { toGetColumnInfo, columnAdd, toGetList, classGet } from "@/api/column";
import { validatePercent, validateNumber } from "@/utils/vm";
import defultImg from "@/assets/defult270.png";
const postForm = {
  name: "", // 专栏名称
  price: 0, // 专栏价格
  status: 1, // 是否上架
  isUpdating: 1, // 是否更新
  subscribers: 0, // 实际订阅量
  initSales: 0, // 虚拟起售数
  sort: 0, // 排序
  columnId: 0,
  cover: "",
  intro: "",
  course: []
};

const statusOptions = [
  // 是否上架
  { key: 1, value: "是" },
  { key: 0, value: "否" }
];
const isUpdateOptions = [
  // 是否更新
  { key: 1, value: "是" },
  { key: 0, value: "否" }
];
const commonOptions = [{ key: 1, value: "是" }, { key: 0, value: "否" }];
const teacherList = [
  // 选择讲师
  { key: 0, value: "老师一啊" },
  { key: 1, value: "老师二啊" }
];

export default {
  components: {
    Tinymce: require("@/components/Tinymce").default
    // imageComponent,
    // ImageCropper
  },
  data() {
    return {
      postForm: Object.assign({}, postForm),
      courseList: [],
      rules: {
        name: [{ required: true, message: "请输入专栏名称", trigger: "blur" }],
        cover: [{ required: true, message: "请选择图片", trigger: "change" }],
        price: [{ required: true, trigger: "blur", validator: validateNumber }],
        clicks: [{ validator: validateNumber, trigger: "blur" }],
        sort: [{ validator: validateNumber, trigger: "blur" }],
        initSales: [{ validator: validateNumber, trigger: "blur" }],
        shareTitle: [
          { min: 0, max: 26, message: "长度在 0 到 26 个字符", trigger: "blur" }
        ],
        shareDesc: [
          { min: 0, max: 29, message: "长度在 0 到 29 个字符", trigger: "blur" }
        ]
      },
      imageUploadUrl: process.env.BASE_API + "/common/course/imageUpload",
      showCourse: false,
      courseName: "",
      courseArray: [],
      classList: []
      // imagecropperKey: 0
    };
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.getColumnInfo();
    this.getClassData();
    // this.selectCourse();
  },
  watch: {
    // 监听路由名称变化 重新调用数据
  },
  methods: {
    getClassData() {
      classGet().then(res => {
        this.classList = res.data.data.data;
      });
    },
    confirmCourse() {
      let courseArray = [];
      for (let i = 0; i < this.courseArray.length; i++) {
        let obj = {
          courseId: this.courseArray[i].courseId,
          name: this.courseArray[i].name,
          price: this.courseArray[i].price
        };
        courseArray.push(obj);
      }
      this.courseArray = courseArray;
      // this.coueseSubmit = courseArray;
      console.log(this.courseArray);
      // console.log(this.coueseSubmit);
      this.showCourse = false;
    },
    handleSelectionChange(val) {
      this.courseArray = val;
    },
    inviteSelect(val) {
      if (val == 0) {
        this.inviteShow = false;
      } else {
        this.inviteShow = true;
      }
    }, // 是否开通邀请卡
    teacherSelect(val) {
      // 是否关联讲师
      if (val == 1) {
        this.teacherShow = true;
      } else {
        this.teacherShow = false;
      }
    },
    courseCommissionSelect(val) {
      // 是否单独设置课程抽成
      if (val == 1) {
        this.courseCommissionShow = true;
      } else {
        this.courseCommissionShow = false;
      }
    },
    submitForm() {
      console.log(this.courseArray);
      if (this.courseArray.length == 0) {
        this.$message({
          type: "warning",
          message: "请选择课程"
        });
        return;
      }
      if (this.postForm.name == "" || this.postForm.name == null) {
        this.$message({
          type: "warning",
          message: "专栏名称必填"
        });
        return;
      }

      var courseId = [];
      for (let i = 0; i < this.courseArray.length; i++) {
        const id = this.courseArray[i].courseId;
        courseId.push(id);
      }
      this.postForm.course = courseId;
      this.postForm.columnId = this.$route.params.columnId;
      columnAdd(this.postForm).then(res => {
        this.$message({
          type: "success",
          message: res.data.data
        });
        this.$router.go(-1);
      });
    },
    searchCourse() {
      getCourseList({ limit: 100000, name: this.courseName }).then(res => {
        this.courseList = res.data.data.list.data;
      });
    },
    async selectCourse() {
      await getCourseList({ limit: 100000 }).then(res => {
        // console.log(res.data.data.list.data);
        this.courseList = res.data.data.list.data;
      });
      this.changeCourse();
    },
    // 选择反显对勾
    changeCourse() {
      var selectArray = [];
      for (let i = 0; i < this.courseList.length; i++) {
        const element = this.courseList[i].courseId;
        for (let j = 0; j < this.courseArray.length; j++) {
          if (element == this.courseArray[j].courseId) {
            selectArray.push(this.courseList[i]);
          }
        }
      }
      selectArray.forEach(row => {
        this.$refs.multipleTable.toggleRowSelection(row);
      });
    },
    getColumnInfo() {
      toGetList({ columnId: this.$route.params.columnId })
        .then(res => {
          this.postForm = res.data.data.columnData.data[0];
          this.courseArray = res.data.data.columnData.data[0].course;
        })
        .catch(err => {
          console.log(err);
        });
    },
    setDefultImg(e) {
      e.target.src = defultImg;
    },
    handleAvatarSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.postForm.cover = response.data.imageUrl;
        this.$message({
          message: "上传成功!",
          type: "info"
        });
      } else {
        this.$message({
          message: "上传失败，请稍候再试!",
          type: "info"
        });
      }
    },
    handleBeforeUpload(file) {
      const isImg = file.type == "image/jpeg" || file.type == "image/png";
      if (!isImg) {
        this.$message.warning("上传图片只能是 JPG 或 PNG 格式");
      }
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
      }
      return isImg && isLt3M;
    }
  }
};
</script>
<style scoped>
.avatar-uploader-icon {
  width: 180px;
  height: 120px;
  line-height: 120px;
}
.avatar {
  width: 180px;
  height: 120px;
}
</style>
